const db = require('../config/database');
const logger = require('../utils/logger');

/**
 * 商品评论管理控制器（简化版）
 * 支持评论创建、查询、回复（一级回复）
 */
class ReviewController {
  /**
   * 手机号脱敏处理
   * 例如：13812345678 -> 138****5678
   */
  maskPhone(phone) {
    if (!phone) return phone;
    const phoneStr = String(phone);
    // 判断是否是手机号格式（11位数字）
    if (/^1\d{10}$/.test(phoneStr)) {
      return phoneStr.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    }
    return phoneStr;
  }

  /**
   * 获取商品评论列表（前台）
   * GET /api/reviews/:productId
   */
  async getReviews(req, res) {
    try {
      const { productId } = req.params;
      const { page = 1, pageSize = 10, rating } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = `
        SELECT r.*, u.username, u.avatar, u.nickname
        FROM product_reviews r
        LEFT JOIN users u ON r.user_id = u.id
        WHERE r.product_id = ? AND r.status = 1
      `;
      const params = [productId];

      if (rating) {
        sql += ' AND r.rating = ?';
        params.push(rating);
      }

      sql += ' ORDER BY r.created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [reviews] = await db.query(sql, params);

      // 处理评论数据
      reviews.forEach(review => {
        // 处理图片字段
        if (review.images) {
          try {
            review.images = JSON.parse(review.images);
          } catch {
            review.images = [];
          }
        } else {
          review.images = [];
        }
        
        // 手机号脱敏：优先使用昵称，如果用户名是手机号则脱敏
        if (review.nickname) {
          review.username = review.nickname;
        } else if (review.username) {
          review.username = this.maskPhone(review.username);
        }
        
        // 删除不需要返回的敏感字段
        delete review.nickname;
      });

      // 获取每个评论的回复
      for (const review of reviews) {
        const [replies] = await db.query(
          `SELECT rr.*, u.username, u.avatar, u.nickname
           FROM review_replies rr
           LEFT JOIN users u ON rr.user_id = u.id
           WHERE rr.review_id = ?
           ORDER BY rr.created_at ASC`,
          [review.id]
        );
        
        // 回复也需要脱敏
        replies.forEach(reply => {
          if (reply.nickname) {
            reply.username = reply.nickname;
          } else if (reply.username) {
            reply.username = this.maskPhone(reply.username);
          }
          delete reply.nickname;
        });
        
        review.replies = replies;
      }

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM product_reviews WHERE product_id = ? AND status = 1';
      const countParams = [productId];

      if (rating) {
        countSql += ' AND rating = ?';
        countParams.push(rating);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: reviews,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取商品评论失败', { error: error.message, productId: req.params.productId });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取商品评分统计（前台）
   * GET /api/reviews/stats/:productId
   */
  async getReviewStats(req, res) {
    try {
      const { productId } = req.params;

      const [stats] = await db.query(
        `SELECT 
          COUNT(*) as total_count,
          AVG(rating) as avg_rating,
          SUM(CASE WHEN rating = 5 THEN 1 ELSE 0 END) as star5_count,
          SUM(CASE WHEN rating = 4 THEN 1 ELSE 0 END) as star4_count,
          SUM(CASE WHEN rating = 3 THEN 1 ELSE 0 END) as star3_count,
          SUM(CASE WHEN rating = 2 THEN 1 ELSE 0 END) as star2_count,
          SUM(CASE WHEN rating = 1 THEN 1 ELSE 0 END) as star1_count
         FROM product_reviews 
         WHERE product_id = ? AND status = 1`,
        [productId]
      );

      res.json({
        success: true,
        data: stats[0]
      });
    } catch (error) {
      logger.error('获取评分统计失败', { error: error.message, productId: req.params.productId });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 创建商品评论（用户）
   * POST /api/reviews
   */
  async createReview(req, res) {
    try {
      const userId = req.user ? req.user.id : null;
      const { product_id, order_no, rating, content, images } = req.body;

      if (!userId) {
        return res.json({ success: false, message: '请先登录' });
      }

      if (!product_id || !content) {
        return res.json({
          success: false,
          message: '商品ID和评论内容不能为空'
        });
      }

      // 检查商品是否存在
      const [products] = await db.query('SELECT id FROM products WHERE id = ?', [product_id]);
      if (products.length === 0) {
        return res.json({ success: false, message: '商品不存在' });
      }

      // 如果提供了订单号，检查订单是否属于该用户且已支付
      if (order_no) {
        const [orders] = await db.query(
          'SELECT id FROM orders WHERE order_no = ? AND user_id = ? AND status = 1',
          [order_no, userId]
        );

        if (orders.length === 0) {
          return res.json({
            success: false,
            message: '订单不存在或未支付，无法评论'
          });
        }

        // 检查是否已评论过
        const [existing] = await db.query(
          'SELECT id FROM product_reviews WHERE order_no = ? AND user_id = ?',
          [order_no, userId]
        );

        if (existing.length > 0) {
          return res.json({
            success: false,
            message: '该订单已评论过'
          });
        }
      }

      // 处理图片
      let imagesValue = null;
      if (images && Array.isArray(images) && images.length > 0) {
        imagesValue = JSON.stringify(images);
      }

      const [result] = await db.query(
        `INSERT INTO product_reviews (product_id, user_id, order_no, rating, content, images, status, created_at) 
         VALUES (?, ?, ?, ?, ?, ?, 1, NOW())`,
        [product_id, userId, order_no || null, rating || 5, content, imagesValue]
      );

      logger.success('创建商品评论成功', { id: result.insertId, product_id, user_id: userId });

      res.json({
        success: true,
        message: '评论成功',
        data: { id: result.insertId }
      });
    } catch (error) {
      logger.error('创建商品评论失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取用户的评论列表（用户）
   * GET /api/reviews/my
   */
  async getMyReviews(req, res) {
    try {
      const userId = req.user ? req.user.id : null;
      const { page = 1, pageSize = 10 } = req.query;
      const offset = (page - 1) * pageSize;

      if (!userId) {
        return res.json({ success: false, message: '请先登录' });
      }

      const [reviews] = await db.query(
        `SELECT r.*, p.name as product_name, p.image as product_image 
         FROM product_reviews r
         LEFT JOIN products p ON r.product_id = p.id
         WHERE r.user_id = ?
         ORDER BY r.created_at DESC
         LIMIT ? OFFSET ?`,
        [userId, parseInt(pageSize), offset]
      );

      // 处理评论图片字段
      reviews.forEach(review => {
        if (review.images) {
          try {
            review.images = JSON.parse(review.images);
          } catch {
            review.images = [];
          }
        } else {
          review.images = [];
        }

        // 处理商品图片
        if (review.product_image) {
          try {
            const parsed = JSON.parse(review.product_image);
            review.product_image = Array.isArray(parsed) ? parsed[0] : parsed;
          } catch {
            // 保持原样
          }
        }
      });

      // 获取总数
      const [countResult] = await db.query(
        'SELECT COUNT(*) as total FROM product_reviews WHERE user_id = ?',
        [userId]
      );

      res.json({
        success: true,
        data: {
          list: reviews,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取用户评论失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // ========== 管理后台专用方法 ==========

  /**
   * 获取所有评论列表（后台管理）
   * GET /api/admin/reviews
   */
  async getReviewsAdmin(req, res) {
    try {
      const { product_id, status, rating, page = 1, pageSize = 10 } = req.query;
      const offset = (page - 1) * pageSize;

      console.log('========== 评论列表查询 ==========');
      console.log('查询参数:', { product_id, status, rating, page, pageSize });

      let sql = `
        SELECT r.*, p.name as product_name, u.username, u.phone 
        FROM product_reviews r
        LEFT JOIN products p ON r.product_id = p.id
        LEFT JOIN users u ON r.user_id = u.id
        WHERE 1=1
      `;
      const params = [];

      if (product_id) {
        sql += ' AND r.product_id = ?';
        params.push(product_id);
      }

      if (status !== undefined && status !== '') {
        sql += ' AND r.status = ?';
        params.push(status);
      }

      if (rating) {
        sql += ' AND r.rating = ?';
        params.push(rating);
      }

      sql += ' ORDER BY r.created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [reviews] = await db.query(sql, params);

      // 处理评论图片字段
      reviews.forEach(review => {
        if (review.images) {
          try {
            review.images = JSON.parse(review.images);
          } catch {
            review.images = [];
          }
        } else {
          review.images = [];
        }
      });

      // 获取每个评论的回复数量
      for (const review of reviews) {
        const [replies] = await db.query(
          'SELECT COUNT(*) as count FROM review_replies WHERE review_id = ?',
          [review.id]
        );
        review.reply_count = replies[0].count;
      }

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM product_reviews WHERE 1=1';
      const countParams = [];

      if (product_id) {
        countSql += ' AND product_id = ?';
        countParams.push(product_id);
      }

      if (status !== undefined && status !== '') {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      if (rating) {
        countSql += ' AND rating = ?';
        countParams.push(rating);
      }

      const [countResult] = await db.query(countSql, countParams);

      console.log('查询到评论数量:', reviews.length);
      console.log('总数:', countResult[0].total);
      console.log('================================');

      res.json({
        success: true,
        data: {
          list: reviews,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取评论列表失败（后台）', { error: error.message });
      console.error('评论查询错误:', error);
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 回复评论（后台管理）
   * POST /api/admin/reviews/:id/reply
   */
  async replyReview(req, res) {
    try {
      const { id } = req.params;
      const { content, admin_name } = req.body;

      if (!content) {
        return res.json({ success: false, message: '回复内容不能为空' });
      }

      // 检查评论是否存在
      const [reviews] = await db.query('SELECT id FROM product_reviews WHERE id = ?', [id]);
      if (reviews.length === 0) {
        return res.json({ success: false, message: '评论不存在' });
      }

      const connection = await db.getConnection();
      await connection.beginTransaction();

      try {
        // 插入回复
        const [result] = await connection.query(
          `INSERT INTO review_replies (review_id, is_admin, admin_name, content, created_at) 
           VALUES (?, 1, ?, ?, NOW())`,
          [id, admin_name || '管理员', content]
        );

        // 更新评论的回复数量
        await connection.query(
          'UPDATE product_reviews SET reply_count = reply_count + 1 WHERE id = ?',
          [id]
        );

        await connection.commit();

        logger.success('回复评论成功', { review_id: id, reply_id: result.insertId });

        res.json({
          success: true,
          message: '回复成功',
          data: { id: result.insertId }
        });
      } catch (error) {
        await connection.rollback();
        throw error;
      } finally {
        connection.release();
      }
    } catch (error) {
      logger.error('回复评论失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 更新评论状态（后台管理）
   * PUT /api/admin/reviews/:id/status
   */
  async updateReviewStatus(req, res) {
    try {
      const { id } = req.params;
      const { status } = req.body;

      if (status === undefined) {
        return res.json({ success: false, message: '状态不能为空' });
      }

      const [result] = await db.query(
        'UPDATE product_reviews SET status = ?, updated_at = NOW() WHERE id = ?',
        [status, id]
      );

      if (result.affectedRows === 0) {
        return res.json({ success: false, message: '评论不存在' });
      }

      logger.success('更新评论状态成功', { id, status });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新评论状态失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 删除评论（后台管理）
   * DELETE /api/admin/reviews/:id
   */
  async deleteReview(req, res) {
    try {
      const { id } = req.params;

      const connection = await db.getConnection();
      await connection.beginTransaction();

      try {
        // 删除所有回复
        await connection.query('DELETE FROM review_replies WHERE review_id = ?', [id]);

        // 删除评论
        const [result] = await connection.query('DELETE FROM product_reviews WHERE id = ?', [id]);

        if (result.affectedRows === 0) {
          await connection.rollback();
          return res.json({ success: false, message: '评论不存在' });
        }

        await connection.commit();

        logger.success('删除评论成功', { id });

        res.json({
          success: true,
          message: '删除成功'
        });
      } catch (error) {
        await connection.rollback();
        throw error;
      } finally {
        connection.release();
      }
    } catch (error) {
      logger.error('删除评论失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  /**
   * 获取评论的所有回复（后台管理）
   * GET /api/admin/reviews/:id/replies
   */
  async getReviewReplies(req, res) {
    try {
      const { id } = req.params;

      const [replies] = await db.query(
        `SELECT rr.*, u.username, u.avatar 
         FROM review_replies rr
         LEFT JOIN users u ON rr.user_id = u.id
         WHERE rr.review_id = ?
         ORDER BY rr.created_at ASC`,
        [id]
      );

      res.json({
        success: true,
        data: replies
      });
    } catch (error) {
      logger.error('获取评论回复失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new ReviewController();

